# -*- coding: utf-8 -*-

from server.storage import Storage
from server.metadata import Metadata
from server.metadata import Tenant

from flask import Flask, request
from flask import make_response
from flask import redirect, url_for
from flask_cors import CORS

app = Flask(__name__)
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))
CORS(app, resources=r'/*')

@app.route('/')
def index():
    path = request.args.get("path")
    print(path)
    return redirect('static/index.html')

@app.route('/imgs/<string:file_id>', methods=['GET'])
def get_imgs(file_id):
    inode = Metadata.getInode(file_id)
    bucketName = str(inode[0], encoding="utf-8")
    filepath = str(inode[1], encoding="utf-8")
    binary = Storage.queryFile(bucketName, filepath)

    resp = make_response(binary) # 响应体数据
    resp.status = 200 # 状态码

    resp.headers['Content-Type'] = 'image/jpeg' # 通过字典的形式添加响应头

    return resp

@app.route('/files/<string:file_id>', methods=['GET'])
def get_file(file_id):
    inode = Metadata.getInode(file_id)
    bucketName = str(inode[0], encoding="utf-8")
    filepath = str(inode[1], encoding="utf-8")
    filename = str(inode[2], encoding="utf-8")
    binary = Storage.queryFile(bucketName, filepath)

    resp = make_response(binary) # 响应体数据
    resp.status = 200 # 状态码

    resp.headers['Content-Type'] = 'application/octet-stream' # 通过字典的形式添加响应头
    resp.headers['Content-disposition'] = 'attachment; filename=' + filename.encode("utf-8").decode("latin1")

    return resp

@app.route('/files', methods=['POST'])
def upload_file():
    appid = request.args.get("appid")
    bucket = request.args.get("bucket")
    secretKey = request.args.get("secretKey")
    # sign = request.args.get("sign")
    fileName = request.args.get("fileName")

    '''
    print(appid)
    print(bucket)
    print(secretKey)
    print(fileName)
    '''

    tenantInfo = Tenant.getTenant(appid)
    tSecretKey = str(tenantInfo[0], encoding="utf-8")
    bucketName = str(tenantInfo[1], encoding="utf-8")

    if bucket == bucketName and secretKey == tSecretKey:
        f = request.files['file']
        fileData = f.read()

        inodeName, inodeInfo = Storage.addFile(bucketName, fileName, fileData)
        Metadata.addInode(inodeName, inodeInfo)

        return inodeName
    else:
        return 'No permission'

if __name__ == '__main__':
    app.run(host="0.0.0.0")
